Warning: mkdir(): No space left on device in /var/www/tg-me/post.php on line 37

Warning: file_put_contents(aCache/aDaily/post/sqlhub/--): Failed to open stream: No such file or directory in /var/www/tg-me/post.php on line 50
Data Science. SQL hub | Telegram Webview: sqlhub/1868 -
Telegram Group & Telegram Channel
👣 Небольшой пример как копировать данные между базами данных используя `go`, `pgx`, и `copy`

Предположим что у нас есть два коннекта к базе (одной или нескольким, это не важно). Далее используя io.Pipe() создаём Reader и Writer, и используя CopyTo() и CopyFrom() переносим данные.

r, w := io.Pipe()

doneChan := make(chan struct{}, 1)

go func() {
defer close(doneChan)

_, err := db1.PgConn().CopyTo(ctx, w, `copy table1 to stdin binary`)
if err != nil {
slog.Error("error", "error", err)
return
}
_ = w.Close()
doneChan <- struct{}{}
}()

_, err = db2.PgConn().CopyFrom(ctx, r, `copy table1 from stdout binary`)
_ = r.Close()

select {
case <-doneChan:
case <-ctx.Done():
}


Вся прелесть тут в том что используем наиболее быстрый способ с точки зрения PostgreSQL.

Используя `copy (select * from where ... order by ... limit ...) to stdout `можем регулировать нагрузку на чтение, следить за прогрессом и управлять копированием данных.

В качестве Reader может выступать что угодно, хоть файл csv, хоть другая СУБД, но тогда данные придётся дополнительно конвертировать в формат понимаемый PostgreSQL - csv или tsv, и использовать copy ... from stdin (format csv).

Нюанс: copy ... from stdin binary , binary обязывает использовать одинаковые типы данных, нельзя будет integer колонку перенести в колонку smallint, если такое требуется, то параметр binary надо опустить.

Весь код тут. И ещё немного кода для вдохновения.

@sqlhub
Please open Telegram to view this post
VIEW IN TELEGRAM



tg-me.com/sqlhub/1868
Create:
Last Update:

👣 Небольшой пример как копировать данные между базами данных используя `go`, `pgx`, и `copy`

Предположим что у нас есть два коннекта к базе (одной или нескольким, это не важно). Далее используя io.Pipe() создаём Reader и Writer, и используя CopyTo() и CopyFrom() переносим данные.


r, w := io.Pipe()

doneChan := make(chan struct{}, 1)

go func() {
defer close(doneChan)

_, err := db1.PgConn().CopyTo(ctx, w, `copy table1 to stdin binary`)
if err != nil {
slog.Error("error", "error", err)
return
}
_ = w.Close()
doneChan <- struct{}{}
}()

_, err = db2.PgConn().CopyFrom(ctx, r, `copy table1 from stdout binary`)
_ = r.Close()

select {
case <-doneChan:
case <-ctx.Done():
}


Вся прелесть тут в том что используем наиболее быстрый способ с точки зрения PostgreSQL.

Используя `copy (select * from where ... order by ... limit ...) to stdout `можем регулировать нагрузку на чтение, следить за прогрессом и управлять копированием данных.

В качестве Reader может выступать что угодно, хоть файл csv, хоть другая СУБД, но тогда данные придётся дополнительно конвертировать в формат понимаемый PostgreSQL - csv или tsv, и использовать copy ... from stdin (format csv).

Нюанс: copy ... from stdin binary , binary обязывает использовать одинаковые типы данных, нельзя будет integer колонку перенести в колонку smallint, если такое требуется, то параметр binary надо опустить.

Весь код тут. И ещё немного кода для вдохновения.

@sqlhub

BY Data Science. SQL hub




Share with your friend now:
tg-me.com/sqlhub/1868

View MORE
Open in Telegram


Data Science SQL hub Telegram | DID YOU KNOW?

Date: |

That strategy is the acquisition of a value-priced company by a growth company. Using the growth company's higher-priced stock for the acquisition can produce outsized revenue and earnings growth. Even better is the use of cash, particularly in a growth period when financial aggressiveness is accepted and even positively viewed.he key public rationale behind this strategy is synergy - the 1+1=3 view. In many cases, synergy does occur and is valuable. However, in other cases, particularly as the strategy gains popularity, it doesn't. Joining two different organizations, workforces and cultures is a challenge. Simply putting two separate organizations together necessarily creates disruptions and conflicts that can undermine both operations.

Can I mute a Telegram group?

In recent times, Telegram has gained a lot of popularity because of the controversy over WhatsApp’s new privacy policy. In January 2021, Telegram was the most downloaded app worldwide and crossed 500 million monthly active users. And with so many active users on the app, people might get messages in bulk from a group or a channel that can be a little irritating. So to get rid of the same, you can mute groups, chats, and channels on Telegram just like WhatsApp. You can mute notifications for one hour, eight hours, or two days, or you can disable notifications forever.

Data Science SQL hub from es


Telegram Data Science. SQL hub
FROM USA